package com.time.workbench.efficient.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.workbench.core.util.AuthUtil;
import com.time.workbench.efficient.entity.bo.ApplicationServer;
import com.time.workbench.efficient.entity.bo.Environment;
import com.time.workbench.efficient.entity.bo.EnvironmentServer;
import com.time.workbench.efficient.entity.dto.SetApplicationServerReq;
import com.time.workbench.efficient.mapper.ApplicationServerMapper;
import com.time.workbench.efficient.mapper.EnvironmentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 应用服务器
 */
@Service
public class ApplicationServerService extends ServiceImpl<ApplicationServerMapper, ApplicationServer> implements IService<ApplicationServer> {


    /**
     * 根据应用和环境获取服务器
     *
     * @param applicationId
     * @param environmentId
     * @return
     */
    public List<ApplicationServer> getApplicationServer(Integer applicationId, Integer environmentId) {
        return lambdaQuery()
                .eq(ApplicationServer::getApplicationId, applicationId)
                .eq(ApplicationServer::getEnvironmentId, environmentId).list();
    }

    public void setServer(SetApplicationServerReq applicationServerReq, Integer applicationId) {
        // 删除原来的应用服务器关系
        LambdaQueryWrapper<ApplicationServer> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        remove(objectLambdaQueryWrapper.eq(ApplicationServer::getApplicationId, applicationId));

        if (CollectionUtil.isNotEmpty(applicationServerReq.getApplicationServers())) {
            applicationServerReq.getApplicationServers().forEach(item -> {
                item.getServerIds().forEach(as -> {
                    ApplicationServer applicationServer = new ApplicationServer();
                    BeanUtils.copyProperties(item,applicationServer);
                    applicationServer.setServerId(as);
                    applicationServer.setApplicationId(applicationId);
                    applicationServer.setTenantId(AuthUtil.getTenantId());
                    save(applicationServer);
                });
            });
        }
    }

}
